package cn.com.anysdk.starter.aspect;

import cn.com.anysdk.ocr.model.OcrResult;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * OCR 服务日志切面
 */
@Slf4j
@Aspect
@Component
public class OcrLoggingAspect {

    @Around("execution(* cn.com.anysdk.ocr.service.IOcrService.recognize(..))")
    public Object logOcrOperation(ProceedingJoinPoint joinPoint) throws Throwable {
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();

        log.debug("开始 OCR 识别操作: {}", methodName);
        long startTime = System.currentTimeMillis();

        try {
            Object result = joinPoint.proceed();
            long duration = System.currentTimeMillis() - startTime;

            if (result instanceof OcrResult) {
                OcrResult ocrResult = (OcrResult) result;
                log.debug("OCR 识别完成，耗时: {}ms, 文本长度: {}, 置信度: {}",
                    duration,
                    ocrResult.getText() != null ? ocrResult.getText().length() : 0,
                    ocrResult.getConfidence());
            } else {
                log.debug("OCR 识别完成，耗时: {}ms", duration);
            }

            return result;
        } catch (Exception e) {
            long duration = System.currentTimeMillis() - startTime;
            log.error("OCR 识别失败，耗时: {}ms", duration, e);
            throw e;
        }
    }
}